<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
session_start();
if(!function_exists('mysqli_connect')){
	die('The <a href="http://www.php.net/manual/en/book.mysqli.php"><strong>mysqli</strong></a> extension for PHP is required to run this installer.');
}
if(file_exists('../config.php')){
	die('config.php file already existed.');
}
function cleanValue($val){
    if ($val == "") return "";
    $val = str_replace( "&#032;", " ", $val );
    $val = str_replace( chr(0xCA), "", $val );  //Remove sneaky spaces
    $val = str_replace( "'", "&#39;", $val ); // IMPORTANT: It helps to increase sql query safety.
    // Ensure unicode chars are OK
    $val = preg_replace("/&amp;#([0-9]+);/s", "&#\\1;", $val );
    // Strip slashes if not already done so.
    if ( get_magic_quotes_gpc() ){
        $val = stripslashes($val);
    }
    // Swop user inputted backslashes
    return $val;
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
	    <!-- Meta, title, CSS, favicons, etc. -->
	    <meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<!-- Latest compiled and minified CSS -->
		<link rel="stylesheet" href="../css/bootstrap.min.css">
		<link rel="stylesheet" href="../css/bootswatch.less.css">
		<!-- Optional theme -->
		<!-- Latest compiled and minified JavaScript -->
		<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
		<title>CyberSlave Install</title>
		<style type="text/css">
		body {
			padding-top: 10px;
		}
		</style>
	</head>
	<body>
		<?php $step = isset($_GET['step']) ? intval($_GET['step']) : 1; $currentStep = 1; $error = null; ?>
		<div class="container-fluid">
			<div class="well">
	          	<div class="panel panel-primary">
					  <!-- Default panel contents -->
					  <div class="panel-heading">Install step <?php echo $strStep = ($step > 2) ? ($step - 1) : $step; ?> of 4</div>
					  <div class="container" style="padding-top:10px;">
						  <?php if(!is_writable('../config-sample.php')): ?>
						  <div class="alert alert-danger">
					    		The <strong>config-sample.php</strong> file is not writable not not found, please CHMOD it to 0755.
					      </div>
						  <?php else: ?>
						  <?php
						  if($step == 2 && isset($_POST['host'])){
						  	if($link = mysqli_connect($_POST['host'], $_POST['username'], $_POST['password'], $_POST['dbname'])){
						  			if($sql = @file_get_contents('cyberslave.sql')){
					  				if(mysqli_multi_query($link, $sql)){
					  					$_SESSION['host'] = $_POST['host'];
					  					$_SESSION['username'] = $_POST['username'];
					  					$_SESSION['password'] = $_POST['password'];
					  					$_SESSION['dbname'] = $_POST['dbname'];

					  					$currentStep = 3;
					  				}
					  				else{
					  					$error = mysqli_error($link);
					  				}
					  			}
					  			else{
					  				$error = 'Could not load queries from <strong>cyberslave.sql</strong> file.';
					  			}
						  	}
							else{
							  	$error = 'Could not connect to MySQL server.';
							}
						  }
						  elseif($step == 4 && isset($_POST['adminusername'])){
					  		$link = mysqli_connect($_SESSION['host'], $_SESSION['username'], $_SESSION['password'], $_SESSION['dbname']);

					  		$_SESSION['salt'] = substr(rtrim(base64_encode(md5(microtime())),"="), 0, 7);

					  		$pwd = md5(md5($_POST['adminpassword']) . $_SESSION['salt']);
					  		$username = cleanValue($_POST['adminusername']);
					  		$email = cleanValue($_POST['adminemail']);

					  		$sql = "INSERT INTO `users` VALUES (null, null, '$username', '$pwd', '$email', 'NO', 'YES', null, 'Asia/Bangkok', 'ADMIN')";
					  		if(mysqli_query($link, $sql)){
					  			$currentStep = 5;
					  		}
					  		else{
					  			$error = 'Could not create admin account: ' . mysqli_error($link);
					  		}
						  }
						  elseif($step == 5 && isset($_POST['appid'])){
						  	$_SESSION['appid'] = cleanValue($_POST['appid']);
						  	$_SESSION['secret'] = cleanValue($_POST['secret']);
		  					// update config file
		  					$arrFind = array('MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DB_NAME', 'YOUR_FACEBOOK_APP_ID', 'APP_SECRET', 'TYPE_ANY_THING_YOU_WANT');
		  					$arrReplace = array($_SESSION['host'], $_SESSION['username'], $_SESSION['password'], $_SESSION['dbname'], $_SESSION['appid'], $_SESSION['secret'], $_SESSION['salt']);
		  					if($strConf = file_get_contents('../config-sample.php')){
		  						$strConf = str_replace($arrFind, $arrReplace, $strConf);
		  						file_put_contents('../config-sample.php', $strConf);
		  						rename('../config-sample.php', '../config.php');
		  						$currentStep = 6;
		  					}
						  }
						  ?>
						  <?php if($error): ?>
						  <div class="alert alert-danger">
					    		<?php echo $error; ?>
					      </div>
						  <?php endif; ?>
						  <?php if($currentStep == 1): ?>
						  <form class="form-horizontal" role="form" method="post" action="?step=2">
							<div class="form-group">
							    <label for="host" class="col-sm-4 control-label">MySQL host</label>
							    <div class="col-sm-4">
							      <input type="text" name="host" class="form-control" id="host" value="localhost">
							    </div>
							</div>
							<div class="form-group">
							    <label for="dbname" class="col-sm-4 control-label">MySQL database name</label>
							    <div class="col-sm-4">
							      <input type="text" name="dbname" class="form-control" id="dbname" value="">
							    </div>
							</div>
							<div class="form-group">
							    <label for="username" class="col-sm-4 control-label">MySQL username</label>
							    <div class="col-sm-4">
							      <input type="text" name="username" class="form-control" id="username" value="">
							    </div>
							</div>
							<div class="form-group">
							    <label for="password" class="col-sm-4 control-label">MySQL password</label>
							    <div class="col-sm-4">
							      <input type="text" name="password" class="form-control" id="password" value="">
							    </div>
							</div>
							<div class="form-group">
								<div class="col-sm-offset-4 col-sm-8">
								  <button type="submit" id="btn-next" class="btn btn-primary">Next step <span class="glyphicon glyphicon-step-forward"></span></button>
								</div>
							</div>
						  </form>
						  <?php endif;//step 1 ?>
						  <?php if($currentStep == 3): ?>
						  <form class="form-horizontal" role="form" method="post" action="?step=4">
							<div class="form-group">
							    <label for="adminusername" class="col-sm-4 control-label">Admin username</label>
							    <div class="col-sm-4">
							      <input type="text" name="adminusername" class="form-control" id="adminusername" value="">
							    </div>
							</div>
							<div class="form-group">
							    <label for="adminemail" class="col-sm-4 control-label">Admin email</label>
							    <div class="col-sm-4">
							      <input type="text" name="adminemail" class="form-control" id="adminemail" value="">
							    </div>
							</div>
							<div class="form-group">
							    <label for="adminpassword" class="col-sm-4 control-label">Admin password</label>
							    <div class="col-sm-4">
							      <input type="text" name="adminpassword" class="form-control" id="adminpassword" value="">
							    </div>
							</div>
							<div class="form-group">
								<div class="col-sm-offset-4 col-sm-8">
								  <button type="submit" id="btn-next" class="btn btn-primary">Next step <span class="glyphicon glyphicon-step-forward"></span></button>
								</div>
							</div>
						  </form>
						  <?php endif; ?>
						  <?php if($currentStep == 5): ?>
						  <form class="form-horizontal" role="form" method="post" action="?step=5">
							<div class="form-group">
							    <label for="appid" class="col-sm-4 control-label">Facebook Application ID</label>
							    <div class="col-sm-4">
							      <input type="text" name="appid" class="form-control" id="appid" value="">
							    </div>
							</div>
							<div class="form-group">
							    <label for="secret" class="col-sm-4 control-label">Application secret key</label>
							    <div class="col-sm-4">
							      <input type="text" name="secret" class="form-control" id="secret" value="">
							    </div>
							</div>
							<div class="form-group">
								<p class="text-center">Don't have Facebook App yet? <a href="https://developers.facebook.com/apps" target="_blank">Create one here</a></p>
							</div>
							<div class="form-group">
								<div class="col-sm-offset-4 col-sm-8">
								  <button type="submit" id="btn-next" class="btn btn-primary">Finish</button>
								</div>
							</div>
						  </form>
						  <?php endif; ?>
						  <?php if($currentStep == 6): ?>
						  <div class="alert alert-success">
					    		Install CyberSlave successful, <a href="../login.php">click here</a> to login.
					      </div>
						  <?php endif; ?>

						  <?php endif; ?>
					</div>
				</div>
	      </div>
		</div>

	</body>
</html>